package admin;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/loginProcess")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 数据库连接信息，实际应用中建议从配置文件读取
    private static final String DB_URL = "jdbc:mysql://localhost:3306/exam";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {



        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 验证参数非空
//        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
//            request.setAttribute("error", "用户名或密码不能为空");
//            request.getRequestDispatcher("adminLogin.jsp").forward(request, response);
//            return;
//        }


        Connectmysql cmysql = new Connectmysql(
                "jdbc:mysql://localhost:3306/exam1",
                "root",
                "root",
                "com.mysql.cj.jdbc.Driver");
        try {
            if(cmysql.open()){

                ResultSet rst= cmysql.executeSql(
                        "SELECT id, name FROM admin WHERE name = ? AND password = ?;",
                        new Object[]{username, password}
                );
                if(rst.next()){
                    //response.getWriter().println("adadadadadadadad");
                    // 登录成功，创建Session并存储用户信息
                    HttpSession session = request.getSession();
                    session.setAttribute("adminId", rst.getInt("id"));
                    session.setAttribute("adminUsername", rst.getString("name"));
                    // 设置Session超时时间（分钟）
                    session.setMaxInactiveInterval(30 * 60);

                    // 重定向到管理主页
                    response.sendRedirect("admin.jsp");

                    System.out.println("哦酷酷酷酷酷酷");



                }else{
                    // 登录失败，返回错误信息
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("adminLogin.jsp").forward(request, response);
                }



//                cmysql.executeSqlUpdate("insert into book values (?,?,?,?,?)", new Object[]{bookid,bookNameText,authorText,time,"无人借阅"});
                //System.out.println("添加成功！");



                rst.close();
            }
        } catch (ClassNotFoundException f) {
            f.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


//        // 数据库连接对象
//        Connection conn = null;
//        // 预编译语句对象
//        PreparedStatement pstmt = null;
//        // 结果集对象
//        ResultSet rs = null;
//
//        try {
//            // 加载数据库驱动
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            // 获取数据库连接
//            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
//
//            // SQL查询语句，使用预编译防止SQL注入
//            String sql = "SELECT id, name FROM admin WHERE name = ? AND passwd = ?";
//            pstmt = conn.prepareStatement(sql);
//            pstmt.setString(1, username);
//            pstmt.setString(2, password);
//
//            // 执行查询
//            rs = pstmt.executeQuery();
//
//            // 验证结果
//            if (rs.next()) {
//                // 登录成功，创建Session并存储用户信息
//                HttpSession session = request.getSession();
//                session.setAttribute("adminId", rs.getInt("id"));
//                session.setAttribute("adminUsername", rs.getString("username"));
//                // 设置Session超时时间（分钟）
//                session.setMaxInactiveInterval(30 * 60);
//
//                // 重定向到管理主页
//                response.sendRedirect("admin/dashboard.jsp");
//            } else {
//                // 登录失败，返回错误信息
//                request.setAttribute("error", "用户名或密码错误");
//                request.getRequestDispatcher("login.jsp").forward(request, response);
//            }
//        } catch (ClassNotFoundException | SQLException e) {
//            e.printStackTrace();
//            // 数据库操作异常处理
//            request.setAttribute("error", "登录过程中发生错误，请稍后再试");
//            //request.getRequestDispatcher("error.jsp").forward(request, response);
//        } finally {
//            // 关闭数据库资源
//            try {
//                if (rs != null) rs.close();
//                if (pstmt != null) pstmt.close();
//                if (conn != null) conn.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
    }
}